﻿using GalaSoft.MvvmLight;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using wp7cinema.Model;
using System.Net;
using System.Linq;
using System.Xml.Linq;
using System;
using GalaSoft.MvvmLight.Command;
using System.Windows;

namespace wp7cinema.ViewModel
{
    public class TicketingInfoViewModel : ViewModelBase
    {
        IEnumerable<MovieItem> allMovies;
        TheaterItem theater;
        MovieItem selectedMovie;
        string selectedDate;

        #region 바인딩될 데이터들..

        private List<string> _enableDates;
        public List<string> EnableDates
        {
            get { return _enableDates; }
            set
            {
                _enableDates = value;
                RaisePropertyChanged("EnableDates");
            }
        }

        private IEnumerable<MovieItem> _movies;
        public IEnumerable<MovieItem> Movies
        {
            get { return _movies; }
            set
            {
                _movies = value;
                RaisePropertyChanged("Movies");
            }
        }

        private IEnumerable<TicketInfo> _tickets;
        public IEnumerable<TicketInfo> Tickets
        {
            get { return _tickets; }
            set
            {
                _tickets = value;
                RaisePropertyChanged("Tickets");
            }
        }
        #endregion

        #region 커맨드들..
        public RelayCommand<MovieItem> SetMovieCommand { get; set; }
        public void SetMovieCommandExecute(MovieItem movie)
        {
            selectedMovie = movie;
            getTicketingInfo();
        }

        public RelayCommand<string> SetDateCommand { get; set; }
        public void SetDateCommandExecute(string date)
        {
            if (date == null) return;
            selectedDate = date;
            getTicketingInfo();
        }

        public RelayCommand<TicketInfo> SetTicketInfo { get; set; }
        public void SetTicketInfoExecute(TicketInfo info)
        {
            if (info == null) return;
            string url = "http://movie.naver.com/movie/reservation/ticketingInfo2.nhn?movie="
                +selectedMovie.Key+"&theater="+theater.Key+"&date="+selectedDate+"&time="+info.Time+"&seats=1&hall="+info.ID;
            WebClient client = new WebClient();
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
            client.DownloadStringAsync(new Uri(url));
        }
        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            string xmlStr = e.Result.Replace("&", "");
            XDocument xdoc = XDocument.Parse(xmlStr);
            string seats = xdoc.Root.Element("ticket").Attribute("seats").Value;
            MessageBox.Show("잔여좌석 : " + seats);
        }
        #endregion

        #region 생성자
        public TicketingInfoViewModel()
        {
            if (IsInDesignMode)
            {
                #region 디자인용 더미데이터
                EnableDates = new List<string> {
                    "20100822","20100823","20100824","20100825","20100826","20100827","20100828"
                };
                Movies = new ObservableCollection<MovieItem> {
                    new MovieItem { Title = "아저씨" },
                    new MovieItem { Title = "아저씨(3D)" },
                    new MovieItem { Title = "아저씨(4bit)" },
                    new MovieItem { Title = "아저씨(디지털)" }
                };
                Tickets = new ObservableCollection<TicketInfo> {
                    new TicketInfo { ViewStr = "1관13시20분" },
                    new TicketInfo { ViewStr = "1관13시20분" },
                    new TicketInfo { ViewStr = "1관13시20분" },
                    new TicketInfo { ViewStr = "1관13시20분" }
                };
                #endregion
            }
            else
            {
                SetMovieCommand = new RelayCommand<MovieItem>(SetMovieCommandExecute);
                SetDateCommand = new RelayCommand<string>(SetDateCommandExecute);
                SetTicketInfo = new RelayCommand<TicketInfo>(SetTicketInfoExecute);

                selectedMovie = App.Current.Resources["MovieInfo"] as MovieItem;
                theater = App.Current.Resources["TheaterInfo"] as TheaterItem;
                allMovies = App.Current.Resources["AllMovies"] as IEnumerable<MovieItem>;

                getTicketingInfo();
            }
        }
        #endregion

        #region 티켓정보(영화목록, 날짜, 시간) 다운로드

        private void getTicketingInfo()
        {
            string url = "http://movie.naver.com/movie/reservation/ticketingInfo2.nhn?movie=" + selectedMovie.Key + "&theater=" + theater.Key;
            if (selectedDate != null) url += "&date=" + selectedDate;
            WebClient client = new WebClient();
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(TicketingInfoDownloaded);
            client.DownloadStringAsync(new Uri(url));
        }
        void TicketingInfoDownloaded(object sender, DownloadStringCompletedEventArgs e)
        {
            XDocument xdoc = XDocument.Parse(e.Result);

            List<string> enableDates = null;
            string dateEnable;
            XAttribute dateEnableAttr = xdoc.Root.Element("dates").Attribute("dateEnable");
            if (dateEnableAttr != null)
            {
                dateEnable = dateEnableAttr.Value;
                enableDates = dateEnable.Split(new string[] { "||" }, StringSplitOptions.RemoveEmptyEntries).ToList();
            }
            int notIncludeCount = 0;
            // 날짜가 같으면 변경하지 않음.
            if (EnableDates != null && enableDates != null)
            {
                notIncludeCount = enableDates.Where(date =>
                {
                    if (EnableDates.Contains(date)) return false;
                    return true;
                }).Count();
            }
            if (EnableDates != null && notIncludeCount == 0 && EnableDates.Count == enableDates.Count)
            {
            }
            else EnableDates = enableDates;

            if (selectedDate != null)
            {
                Tickets = xdoc.Root.Element("tickets").Elements("info")
                    .Select(info => new TicketInfo
                    {
                        ViewStr = info.Attribute("place").Value,
                        ID = info.Attribute("id").Value,
                        Time = info.Attribute("time").Value
                    });
            }

            if (Movies != null) return;

            IEnumerable<string> movies = xdoc.Root.Element("movies").Elements("item")
                .Select(item => item.Attribute("key").Value);

            Movies = allMovies.Where(item =>
            {
                if (movies.Contains(item.Key)) return true;
                return false;
            });
        }
        #endregion

        ////public override void Cleanup()
        ////{
        ////    // Clean own resources if needed

        ////    base.Cleanup();
        ////}
    }
}